﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace DNNXHR
{
    public class XHRPortalModule : DotNetNuke.Entities.Modules.PortalModuleBase
    {
        public delegate string XHRCall(string Params);


        Dictionary<string, XHRCall> _ClientMethods = new Dictionary<string, XHRCall>();
        public Dictionary<string, XHRCall> ClientMethods { get { return _ClientMethods; } set { _ClientMethods = value; } }

        public bool IsXHR
        {
            get { return Page.Request["XHR"] == "true"; }
        }
        public string JSFunctionTemplate = "function [NAME](params, callback) { return XHR('[NAME]', params, callback); }";
        protected override void OnInit(EventArgs e)
        {

            if (IsXHR)
            {
                string x = Page.Request["x"];
                string p = Page.Request["p"];
                if (x != null && x != "")
                {
                    if (ClientMethods.ContainsKey(x))
                    {
                        Page.Response.Clear();
                        XHRCall c = ClientMethods[x];
                        Page.Response.Write(c.Invoke(p));
                        Page.Response.End();
                    }
                }
            }
            else
            {
                Page.ClientScript.RegisterClientScriptInclude("XHR", Page.Request.ApplicationPath + "/DesktopModules/Dynamo/js/xhr.js");
                Page.ClientScript.RegisterClientScriptInclude("JQUERY", "http://ajax.microsoft.com/ajax/jquery.ui/1.8.5/jquery-ui.js");
                System.Text.StringBuilder sb = new System.Text.StringBuilder();
                sb.Append("<script type='text/javascript'>");
                foreach (string name in ClientMethods.Keys)
                {
                    sb.Append(JSFunctionTemplate.Replace("[NAME]", name));
                }
                sb.Append("</script>");
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "xhr", sb.ToString());



            }
            base.OnInit(e);


        }

    }
}